﻿using System;
using System.Collections.Generic;
using System.Configuration;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Extensions;
using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of CommTemplates
	/// </summary>
	public partial class CommTemplates : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		private bool m_bRebindGrid = false;

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// If need to rebind...
			if (m_bRebindGrid)
			{

				// Get the current user id
				MySession mySession = MySession.BindMySession();
				int iUserId = mySession.UserID;
#if DEBUG
				if (iUserId == 0)
					iUserId = 1;
#endif // #if DEBUG

				// Declare an entity view model
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Load the template view model
					CommTemplateListModel m = new CommTemplateListModel(ent,iUserId);
					gridTemplates.DataSource = m.Elements;
					gridTemplates.DataBind();

				}

			}

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

			}
			else
			{

				// Color the panels
				MyApplication myApp = MyApplication.BindMyApplication();
				gridTemplates.RowStyle.BorderColor = MyApplication.BindMyApplication().SecondaryWebColor;
				pnlOptions.BackColor = MyApplication.BindMyApplication().PrimaryWebColor;

				// Rebind the grid
				m_bRebindGrid = true;

			}

		}

		protected void gridTemplates_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			// If this is a row...
			if (e.Row.RowType == DataControlRowType.DataRow)
			{

				// Get the item tag
				CommTemplateListModel.Element el = e.Row.DataItem as CommTemplateListModel.Element;

				// Load the actions dropdown
				DropDownList cboAction = e.Row.FindControl("cboAction") as DropDownList;
				cboAction.Items.Add("[Actions...]");
				if (el.UsageCount == 0)
					cboAction.Items.Add("Edit");
				cboAction.Items.Add("Clone");

				// Enable/disable delete button
				Button butDelete = e.Row.FindControl("butDelete") as Button;
				if (el.UsageCount > 0)
					butDelete.Enabled = false;
				else
					butDelete.OnClientClick = "return confirmDeleteTemplate();";

			}

		}

		protected void butDelete_Click(object sender, EventArgs e)
		{

			// Get the parent row
			GridViewRow row = (sender as Control).GetParentObject(typeof(GridViewRow)) as GridViewRow;
			int iCommTemplateId = int.Parse(gridTemplates.DataKeys[row.RowIndex].Value.ToString());

			// Get the current user id
			MySession mySession = MySession.BindMySession();
			int iUserId = mySession.UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Get the template folder path
			string strTemplateFolderPath = ConfigurationManager.AppSettings["TemplateRootFolderPath"];

			// Delete the selected template
			string strError = null;
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{
				strError = CommTemplate.Delete(ent, iCommTemplateId, strTemplateFolderPath, iUserId);
			}
			if (strError != null)
				(this.Master as FinanceMaster).ErrorMessage = strError;
			else
				m_bRebindGrid = true;

		}

		protected void cboAction_SelectedIndexChanged(object sender, EventArgs e)
		{

			// Declaration of local variables
			string strError = null;

			// Get the parent row
			GridViewRow row = (sender as Control).GetParentObject(typeof(GridViewRow)) as GridViewRow;
			int iCommTemplateId = int.Parse(gridTemplates.DataKeys[row.RowIndex].Value.ToString());

			// Get the current user id
			MySession mySession = MySession.BindMySession();
			int iUserId = mySession.UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Get the template folder path
			string strTemplateFolderPath = ConfigurationManager.AppSettings["TemplateRootFolderPath"];

			// Get the selected action
			string strAction = (sender as DropDownList).SelectedValue;
			if (strAction == "Clone")
			{

				// Clone the selected template
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{
					strError = CommTemplate.Clone(ent, iCommTemplateId, strTemplateFolderPath, iUserId);
				}
				if (strError != null)
					(this.Master as FinanceMaster).ErrorMessage = strError;
				else
					m_bRebindGrid = true;

			}
			else if (strAction == "Edit")
			{

				// Declare a repository
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Lock the template
					strError = RecentActivity.AttemptLock(ent, "tbCommTemplate", iCommTemplateId, iUserId);
					if (strError == null)
					{

						// Get the template type
						Definitions.eCommTemplateType templateType = CommTemplate.GetTemplateType(ent, iCommTemplateId);
						if (templateType == Definitions.eCommTemplateType.Letter)
						{

							// Edit the template
							mySession.SetHandover("CommTemplateLetterEditor.aspx", iCommTemplateId);
							Response.Redirect("~/Finance/CommTemplateLetterEditor.aspx");

						}
						else
						{

							// Edit the template
							mySession.SetHandover("CommTemplateEmailEditor.aspx", iCommTemplateId);
							Response.Redirect("~/Finance/CommTemplateEmailEditor.aspx");

						}

					}

				}

			}
			else if (strAction == "Queue")
			{

				// Declare a repository
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Lock the template
					strError = RecentActivity.AttemptLock(ent, "tbCommTemplate", iCommTemplateId, iUserId);
					if (strError == null)
					{

						// Get the template type
						Definitions.eCommTemplateType templateType = CommTemplate.GetTemplateType(ent, iCommTemplateId);
						if (templateType == Definitions.eCommTemplateType.Email)
						{

							// Development message
							strError = Definitions.DevelopmentMessage;

						}
						else if (templateType == Definitions.eCommTemplateType.Letter)
						{

							// Development message
							strError = Definitions.DevelopmentMessage;

						}

					}

				}

			}

			// Show the error
			(this.Master as FinanceMaster).ErrorMessage = strError;

		}

		protected void hypNewEmail_Click(object sender, EventArgs e)
		{

			// Redirect to editing page
			MySession mySession = MySession.BindMySession();
			mySession.SetHandover("CommTemplateEmailEditor.aspx", -1);
			Response.Redirect("~/Finance/CommTemplateEmailEditor.aspx");

		}

		protected void hypNewOffice_Click(object sender, EventArgs e)
		{

			// Redirect to editing page
			MySession mySession = MySession.BindMySession();
			mySession.SetHandover("CommTemplateLetterEditor.aspx", -1);
			Response.Redirect("~/Finance/CommTemplateLetterEditor.aspx");

		}

	}

}